package tjs.study.notes.dotest.jvm.classload;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Nicky.Tang on 2021/10/20 12:08 下午
 *
 * @since 02.12.10
 */
public class OtherPackagerUrlClassLoader extends URLClassLoader {
    // OtherPackagerUrlClassLoader由AppClassLoader加载
    public static boolean firstFlag = true;

    public OtherPackagerUrlClassLoader(List<String> urlStrs) {
        super(toURLs(urlStrs));
    }

    public OtherPackagerUrlClassLoader(URL[] urls) {
        super(urls);
    }

    public static URL[] toURLs(List<String> urlStrs) {
        URL[] urls = new URL[urlStrs.size()];
        for (int i = 0; i < urlStrs.size(); i++) {
            try {
                urls[i] = new URL("file:" + urlStrs.get(i));
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
        return urls;
    }

    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        Class<?> loadedClass = this.findLoadedClass(name);
        if("tjs.study.notes.dotest.jvm.classload.OtherPackagerUrlClassLoader".equals(name)){
            // 避免重复运行main方法，持有是否启动标识的类，由AppClassLoader加载
            loadedClass = super.loadClass(name, resolve);
        }
        if (loadedClass == null) {
            try {
                // 优先尝试从当前路径加载
                loadedClass = this.findClass(name);
            } catch (Exception var9) {
                // 当前路径没有，再从父加载器加载
                loadedClass = super.loadClass(name, resolve);
            }
        }

        if (resolve) {
            this.resolveClass(loadedClass);
        }
        return loadedClass;
    }

    public static void main(String[] args) throws ClassNotFoundException {
        OtherPackagerUrlClassLoader urlClassLoader = new OtherPackagerUrlClassLoader(
                Arrays.asList("/Users/piangpiang/Documents/software/apache-maven-3.6.1/my_maven_ws/TJS/study/notes/jvm-utils/v2.0/jvm-utils-v2.0.jar")
        );
        Class<?> clashStringUtils = urlClassLoader.loadClass("tjs.study.notes.jvm.utils.ClashStringUtils");
    }
}
